package com.zw.controller;

import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zw.entity.Commodity;
import com.zw.entity.Shopping;
import com.zw.entity.User;
import com.zw.service.CommodityService;
import com.zw.service.ShoppingService;

@Controller
public class ShoppingController {

	@Autowired
	private ShoppingService shoppingService;
	
	@Autowired
	private CommodityService commodityService;
	
	@ResponseBody
	@RequestMapping("/insertShopping")
	public String insertShopping(Commodity commodity,HttpServletRequest request){
		Shopping shopping=new Shopping();
		shopping.setCommodityid(commodity.getCommodityid());
		double d=commodity.getCommoditycount()*commodity.getCommodityprice().doubleValue();
		shopping.setCountprice(BigDecimal.valueOf(d));
		HttpSession session=request.getSession();
		User user=(User) session.getAttribute("user");
		shopping.setUserid(user.getUserid());
		shopping.setNum(commodity.getCommoditycount());
		int staticid=shoppingService.insertShopping(shopping);
		if(staticid>0)
			return "success";
		else 
			return "error";
	}
	
	@RequestMapping("/selectShopping")
	public ModelAndView selectShopping(HttpServletRequest request){
		User user=(User) request.getSession().getAttribute("user");
		List<Shopping> list=shoppingService.selectShopping(user.getUserid());
		list.stream().forEach(shopping ->{
			shopping.setCommodity(commodityService.select(shopping.getCommodityid()));
		});
		ModelAndView mav=new ModelAndView("/shopping");
		mav.addObject("shopList", list);
		return mav;
	}
}
